<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error="error"
      error-text="加载失败,请点击重试!"
      @load="onLoad"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
      />
    </van-list>
  </div>
</template>

<script>
// 加载获取搜索结果请求的方法
import { getSearchResult } from '@/api/search'

export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 10,
      error: false
    }
  },
  methods: {
    async onLoad() {
      try {
        // 1.请求获取数据
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.perPage,
          q: this.searchText
        })
        // 2.添加数据
        const { results } = data.data
        this.list.push(...results)
        // 3.关闭loading状态
        this.loading = false
        // 4.判断是否还有更多数据
        if (results.length) {
          // 有,就继续加载
          this.page++
        } else {
          // 没,关闭加载状态
          this.finished = false
        }
      } catch (err) {
        // 加载失败,展示提示状态
        this.error = true
        // 关闭加载状态
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>